<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>JSON格式化</title>
    <link href="https://www.sunyuchao.com/static/layui/css/layui.css"  rel="stylesheet">

    <link href="https://www.sunyuchao.com/static/css/fontawesome4.7.0/css/font-awesome.css"  rel="stylesheet">
    <link href="https://www.sunyuchao.com/static/css/common.css" rel="stylesheet">

    <link href="https://www.sunyuchao.com/static/css/utilscommon.css" rel="stylesheet">
    <link href="https://www.sunyuchao.com/static/css/reply.css" rel="stylesheet">
    <script th:src="${iconfontUrl}"></script>

    <style>
        .tab-wrap{background-color: white;padding: 3px 10px;margin-top: 10px;}
        .tab-wrap .tab-wrap-square{padding: 5px;margin-bottom: 10px;position: relative;border-bottom: 1px solid #e7e7e7;
            padding-bottom: 10px;padding-top: 12px;}
        .tab-wrap .tab-wrap-square::after {
            position: absolute;
            left: 0;
            bottom: 0;
            height: 2.5px!important;
            width: 100px;
            background-color: #51aded;
            content: '';
            transition:width 2s;
            -moz-transition:width 2s; /* Firefox 4 */
            -webkit-transition:width 2s; /* Safari and Chrome */
            -o-transition:width 2s; /* Opera */
        }
        /*鼠标悬停div修改子元素样式*/
        .tab-wrap:hover .tab-wrap-square:first-child::after{
            width: 400px;
        }

        .tab-wrap .reply-all-head{font-size: 18px;font-weight: bold;}
        /*手机*/
        @media screen and (max-width: 980px) {
            .smb-right{width:88%;}
        }
    </style>
</head>
<body>
<!--搜索-->
<div th:replace="index :: search"></div>
<!--右下角固定-->
<div th:replace="index :: permanent"></div>
    <div th:replace="index :: top"></div>
    <div class="content">
        <h1 class="square">
            <span class="f-right">曾经沧海难为水，除却巫山不是云 —— 元稹</span>
        </h1>
        <input type="hidden" th:value="${bindId}" name="id">
        <div class="left">
            <h2>JSON数据格式化</h2>
            <textarea id="origin" class="layui-textarea" style="height: 400px;margin-top: 10px;" placeholder="请将JSON格式数据放到这里"></textarea>
            <div class="layui-btn-container" style="margin-top: 10px;">
                <button class="layui-btn layui-btn-normal" id="format">格式化校验</button>
                <button class="layui-btn layui-btn-normal" id="press">压缩</button>
                <button class="layui-btn layui-btn-normal" data-clipboard-target="#origin" id="copy">复制到剪切板</button>
                <button class="layui-btn layui-btn-disabled">功能4</button>
                <button class="layui-btn layui-btn-disabled">功能5</button>
                <button class="layui-btn layui-btn-disabled">功能6</button>
            </div>

            <div class="tab-wrap" style="padding: 10px 20px;">
                <h3 class="tab-wrap-square">留言评论</h3>

                <div th:replace="onlineutils/linux :: messageBox"></div>
                <h2 class="reply-all-head">所有回复</h2>
                <div th:replace="onlineutils/linux :: comment"></div>
                <div th:if="${pageTotal != 0}" class="layui-btn-container" style="margin-top: 20px;">
                    <a th:href="@{/message(page=${page-1},bindId=${bindId})}" th:class="${page == 1 ? 'layui-btn layui-btn-disabled':'layui-btn'}"> <i class="layui-icon layui-icon-left"></i></a>
                    <a th:href="@{/message(page=${num},bindId=${bindId})}" th:class="${num == page ? 'layui-btn layui-btn-normal':'layui-btn'}" th:each="num : ${pageNumList}" th:text="${num}"></a>
                    <a th:href="@{/message(page=${page+1},bindId=${bindId})}" th:class="${page == pageTotal ? 'layui-btn layui-btn-disabled':'layui-btn'}"> <i class="layui-icon layui-icon-right"></i></a>
                </div>
            </div>
        </div>
        <div class="right">
            <div style="width: 100%;height: 200px;background-color: #cdd;margin-top: 20px;">

            </div>
            <div style="width: 100%;height: 200px;background-color: #cdf;margin-top: 20px;">

            </div>
            <div style="width: 100%;height: 200px;background-color: #dfc;margin-top: 20px;">

            </div>
        </div>
    </div>


    <script src="https://www.sunyuchao.com/static/js/heart.js" ></script>
    <script src="https://www.sunyuchao.com/static/layui/layui.js"></script>
    <script src="https://www.sunyuchao.com/static/js/clipboard.min.js"></script>
    <script src="https://www.sunyuchao.com/static/js/jquery3.3.1.min.js"></script>
    <script src="https://www.sunyuchao.com/static/js/reply.js"></script>

    <script src="https://www.sunyuchao.com/static/js/common.js"></script>
    <!--子回复模板-->
    <script type="text/template" id="childMsg">
        <div class="msg-history">
            <div class="mh-left">
                <img class="radius" src="{avatar}" width="40" height="40">
            </div>
            <div class="mh-right">
                <input type="hidden" class="userId" value="{userId}">
                <p>
                        <span style="float: left;"><span><a class="comment" href="javascript:;">{commentUsername}</a></span> 回复  <span>
                            <a href="javascript:;" class="commented">{commentedUsername}</a></span></span>
                    <span style="float: right;" class="timeago" datetime="{time}"></span>
                </p>
                <p class="reply-content">
                    {content}
                </p>
                <p class="operate">
                    <span class="muted"> <a onclick="openChildReply(this)" href="javascript:;">回复</a></span>
                </p>
            </div>
            <hr>
        </div>
        <div class="layui-clear"></div>
    </script>
    <!--1级回复模板-->
    <script type="text/template" id="FirstMsg">
        <li class="item">
            <div class="item-left">
                <img class="radius" src="{avatar}" width="50" height="50">
            </div>
            <div class="item-right">
                <p>
                    <span style="float: left;"><a href="javascript:;" class="floor">{commentUsername}</a></span>
                    <span style="float: right;" class="timeago" datetime="{time}"></span>
                </p>
                <p class="reply-content">
                    {content}
                </p>
                <p class="operate">
                    <span class="muted"> <a class="show" onclick="show(this)" href="javascript:;">展开</a>(<span>0</span>)</span>
                    <span class="muted"> <a onclick="openReply(this)" href="javascript:;">回复</a></span>
                    <span class="muted"> <a href="#"><i class="layui-icon layui-icon-praise"></i>17</a></span>
                    <span class="muted"> <a href="#"><i class="layui-icon layui-icon-tread"></i>17</a></span>
                </p>
                <div class="msg-content">

                </div>
                <div class="item-child-smbx">
                    <input type="hidden" class="receiverUserId" value="{commentId}">
                    回复 <span class="receiver">{commentUsernameCopy}</span>
                    <div contenteditable="true" class="layui-textarea" placeholder=""></div>
                    <div class="smb-r-bottom">
                        <a onclick="loadFace(this)" href="javascript:;"><img src="/layui/images/face/1.gif"></a>
                        <div class="face-frame"></div>
                        <button onclick="saveMsg(this)" class="layui-btn layui-btn-normal" style="float: right;margin-right: 8px;">留言</button>
                    </div>
                </div>

            </div>
            <div class="layui-clear"></div>
        </li>
    </script>

    <script th:inline="javascript">
        var currentUser=[[${session.loginUser}]];
        var currentUserId;
        if(currentUser != null){
            currentUserId=currentUser.id;
        }
    </script>
    <script>
        /**
         * 留言给我
         * */
        function msgToMe(obj) {
            var frameObj = $(obj).parent().prev();
            var replyEntity={};
            replyEntity.content = $(frameObj).html().replace(/&nbsp;/ig,'');;//回复内容
            replyEntity.commentedUserId=1;//被回复者默认是我（生产中放到后台）
            replyEntity.level = 1;
            replyEntity.type = 5;
            replyEntity.userId=currentUserId;
            replyEntity.bindId=$("input[name=id]").val();
            if($.trim(replyEntity.content).length == 0){
                alert("请输入内容")
                return false;
            }
            var retInfo={};
            var flag=false;
            $.ajax({
                url:"/userComment/saveFirstMessage",
                type:"POST",
                data:replyEntity,
                async:false,
                success:function (e) {
                    if(e.success){
                        retInfo=e.data;
                        flag=true;
                    }else{
                        layui.layer.alert(e.message);
                    }
                },dataType: "json"
            });
            //校验
            if(!flag){
                return;
            }
            var html=$("#FirstMsg").html();
            var arr = [];
            arr.push(formatTemplate(retInfo, html));
            $("#message-comment-body").prepend(arr.join(''));
            $(frameObj).html("");//清空文本域
            layui.timeago.render($('.timeago'));
        }




        /**
         * 保存评论
         * */
        function saveMsg(obj,parentId){

            //获取回复信息
            var frameObj = $(obj).parent().prev();
            var msg = $(frameObj).html().replace(/&nbsp;/ig,'');;//回复信息
            var receiver = $(obj).parent().parent().children(".receiver");
            var receiverUserId = $(obj).parent().parent().children(".receiverUserId");
            var commented = $(receiver).html();
            var commentedId = $(receiverUserId).val();
            var replyEntity={};
            replyEntity.userId=currentUserId;
            replyEntity.commentedUserId=commentedId;
            replyEntity.content=msg;
            replyEntity.level=2;
            replyEntity.type=5;
            replyEntity.bindId=$("input[name=id]").val();
            replyEntity.parentId=parentId;
            var flag=false;
            var retInfo={};
            $.ajax({
                url:"/userComment/saveChildrenMessage",
                type:"POST",
                data:replyEntity,
                async:false,
                success:function (e) {
                    if(e.success){
                        retInfo=e.data;
                        flag=true;
                    }else{
                        layui.layer.alert(e.message);
                    }
                },dataType:"json"
            });
            //校验
            if(!flag){
                return;
            }
            var prev = $(obj).parent().parent().prev();
            if($(prev).is(":hidden")){
                $(prev).show();
            }

            var html = $("#childMsg").html();
            var arr = [];
            arr.push(formatTemplate(retInfo, html));
            $(prev).append(arr.join(''));//追加回复信息
            var show = $(obj).parent().parent().prev().prev().find(".show");//展开按钮
            $(show).html("关闭");

            $(frameObj).html("");//清空回复框
            layui.timeago.render($('.timeago'));
        }
    </script>
    <script>
        layui.config({base:'https://www.sunyuchao.com/static/layui/extends/'});
        layui.use(['layer','timeago'], function(){
               var layer = layui.layer,
                   timeago=layui.timeago,
                $ = layui.jquery;
            timeago.render($('.timeago'));

            $("#format").click(function () {
                var s = formatJson($("#origin").val());
                $("#origin").val(s);

            });
            //必须要初始化 第一种初始化
            var clipboard = new ClipboardJS('#copy');
            clipboard.on('success', function(e) {
                layer.msg("成功复制到剪切板")
            });
            clipboard.on('error', function(e) {
                layer.msg("复制失败")
            });


            $("#press").click(function () {
                var json = $("#origin").val();
                json=json.replace(/\s+/g, "");
                $("#origin").val(json);
            });


            var formatJson = function(json, options) {
                var reg = null, formatted = '', pad = 0, PADDING = '    '; // 也可以用\t来做

                options = options || {};
                //删除'{'或'['跟在':'后面的换行符
                options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true);
                // 在冒号后面加空格
                options.spaceAfterColon = (options.spaceAfterColon !== false);

                // 开始格式化

                // 确保是字符串
                if (typeof json !== 'string') {
                    json = JSON.stringify(json);
                }
                // 去除空行
                try {
                    json = JSON.parse(json);
                    json = JSON.stringify(json);
                }catch (e) {
                    layer.alert("json格式错误") ;
                    return;
                }

                // 在花括号前后添加换行
                reg = /([{}])/g;
                json = json.replace(reg, '\r\n$1\r\n');

                // 在方括号前后添加换行
                reg = /([\[\]])/g;
                json = json.replace(reg, '\r\n$1\r\n');

                // 在逗号后面添加换行
                reg = /(,)/g;
                json = json.replace(reg, '$1\r\n');

                // 删除多个换行
                reg = /(\r\n\r\n)/g;
                json = json.replace(reg, '\r\n');

                // 删除逗号前的换行
                reg = /\r\n\,/g;
                json = json.replace(reg, ',');

                // optional formatting...
                if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
                    reg = /\:\r\n\{/g;
                    json = json.replace(reg, ':{');
                    reg = /\:\r\n\[/g;
                    json = json.replace(reg, ':[');
                }
                if (options.spaceAfterColon) {
                    reg = /\:/g;
                    json = json.replace(reg, ' : ');
                }

                $.each(json.split('\r\n'), function(index, node) {
                    var i = 0, indent = 0, padding = '';

                    if (node.match(/\{$/) || node.match(/\[$/)) {
                        indent = 1;
                    } else if (node.match(/\}/) || node.match(/\]/)) {
                        if (pad !== 0) {
                            pad -= 1;
                        }
                    } else {
                        indent = 0;
                    }

                    for (i = 0; i < pad; i++) {
                        padding += PADDING;
                    }

                    formatted += padding + node + '\r\n';
                    pad += indent;
                });
                return formatted;
            };
        });
    </script>
</body>
<script src="/login.js"></script>
</html>